from django.conf import settings
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View
from fdfs_client.client import Fdfs_client
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.views import APIView

from ten_times.utils.fastdfs.storage import FastDFSStorage


class UploadView(View):
    def post(self, request):
        avatar = request.FILES.get('img').read()
        print(type(avatar))
        if not avatar:
            return JsonResponse({'code': 400, 'errmsg': '没有数据'})

        client = Fdfs_client(settings.FDFS_CLIENT_CONF)

        res = client.upload_by_buffer(avatar)

        file_id = res.get('Remote file_id')
        imgurl = settings.FDFS_URL + file_id

        return JsonResponse({'imgurl': imgurl})


# 前端富文本编辑器上传图片
class CommonView(View):
    def post(self, request):
        upload = request.FILES.get('upload')

        if not upload:
            return JsonResponse({'code': 400, 'errmsg': '没有文件'})
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        res = client.upload_by_buffer(upload.read())
        file_id = res.get('Remote file_id')
        imgurl = settings.FDFS_URL + file_id

        return redirect('http://www.tentimes.site:8080/upload_success.html?image_url=%s' % imgurl)
